package is.glif.fenius.webui.resv;

import java.util.ArrayList;

import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import is.glif.fenius.webui.client.Requester;
import is.glif.fenius.webui.common.WebUIException;
import is.glif.fenius.webui.db.bean.Component;
import is.glif.fenius.webui.db.bean.CompositeReservation;
import is.glif.fenius.webui.db.bean.WebReserveRequest;
import is.glif.fenius.webui.topo.DjikstraPathProvider;

public class Decomposer {
    private static Decomposer instance;
    public static Decomposer getInstance() {
        if (instance == null) {
            instance = new Decomposer();
        }
        return instance;
    }
    
    private Decomposer() {
    }
    
    private static Logger log = Logger.getLogger(Decomposer.class);
    
    public JSONObject reserve(WebReserveRequest webreq) throws WebUIException {
        JSONObject result = new JSONObject();
        String src = webreq.getSrc();
        String dst = webreq.getDst();
        JSONArray path = null;
        ArrayList<Component> comps = new ArrayList<Component>();
        try {
            path = DjikstraPathProvider.getInstance().getPath(src, dst);
            // System.out.println(output);
            String netId = null;
            Component comp = null;
            int compIdx = 0;
            for (int i = 0; i < path.length(); i++) {
                JSONObject hop = path.getJSONObject(i);
                if (hop.has("network")) {
                    if (hop.getString("network").equals(netId)) {
                        comp = comps.get(compIdx);
                        comp.setEndpointZ(hop.getString("urn"));
                    } else {
                        if (netId != null) {
                            compIdx++;
                        }
                        netId = hop.getString("network");
                        comp = new Component();
                        comp.setNetworkId(netId);
                        comp.setEndpointA(hop.getString("urn"));
                        comps.add(comp);
                    }
                }
            }
            JSONObject obj = new JSONObject();
            obj.put("items", path);
            result.put("path", path);
        } catch (JSONException e) {
            log.error(e);
            e.printStackTrace();
            throw new WebUIException("Internal error");
        }
        
        CompositeReservation composite = new CompositeReservation();
        for (Component comp : comps) {
            System.out.println("COMPONENT: "+comp.getNetworkId()+" : "+comp.getEndpointA()+" -- "+comp.getEndpointZ());
            composite.getComponents().add(comp);
        }
        composite.setWebReserveRequest(webreq);
        webreq.setCompositeReservation(composite);
        Requester.getInstance().reserve(composite);
        return result;
        
    }
   
}
